package com.hdoit.ares.web.insu.controllers;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.acc.service.IAwardSettingService;
import com.hdoit.ares.logical.brokerage.service.IBrokerageRecordService;
import com.hdoit.ares.logical.brokerage.service.ICarBrokerageRecordService;
import com.hdoit.ares.logical.brokerage.service.ICarShareBrokerageService;
import com.hdoit.ares.logical.brokerage.service.IShareBrokerageService;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.insu.model.Insurance;
import com.hdoit.ares.logical.insu.model.InsurancePeople;
import com.hdoit.ares.logical.insu.service.IInsuranceInsurancePeopleService;
import com.hdoit.ares.logical.insu.service.IInsurancePeopleService;
import com.hdoit.ares.logical.insu.service.IInsuranceService;
import com.hdoit.ares.logical.personnel.service.IPersonnelService;
import com.hdoit.ares.logical.team.service.ICooperationTeamService;
import com.hdoit.ares.logical.viewmodel.cust.CustomerSearch;
import com.hdoit.ares.logical.viewmodel.cust.LoginRole;
import com.hdoit.ares.logical.viewmodel.insu.InsuranceSearch;
import com.hdoit.ares.selfcommon.enums.acc.InsuranceType;
import com.hdoit.ares.selfcommon.enums.insu.InsuranceState;
import com.hdoit.ares.selfcommon.enums.insu.InsuranceStatus;
import com.hdoit.ares.selfcommon.utils.ExpressionUtil;
import com.tennetcn.common.enums.ManageContainer;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.enums.pub.YesOrNo;
import com.tennetcn.common.logical.superbase.service.IRoleEmployeeService;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.utils.ChineseUtils;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.JsonUtils;
import com.tennetcn.component.web.ActionResult;
import com.tennetcn.component.web.BaseController;
import com.tennetcn.component.web.ErrorResult;
import com.tennetcn.component.web.JsonActionResult;

/**
 * @author      lvsi
 * @email       
 * @createtime  2017年12月09日 20:45:07
 * @comment
 */
@Controller
@RequestMapping(value = "/admin/insu/insurance/")
public class InsuranceController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/admin/insu/insurance/";
    }

    private IPersonnelService personnelService;
    
    public IPersonnelService getPersonnelService() {
		return personnelService;
	}
    @Resource
	public void setPersonnelService(IPersonnelService personnelService) {
		this.personnelService = personnelService;
	}

	private IAwardSettingService awardSettingService;
    public IAwardSettingService getAwardSettingService() {
		return awardSettingService;
	}
    @Resource
	public void setAwardSettingService(IAwardSettingService awardSettingService) {
		this.awardSettingService = awardSettingService;
	}

	private IInsurancePeopleService insurancePeopleService;
    public IInsurancePeopleService getInsurancePeopleService() {
		return insurancePeopleService;
	}
    @Resource
	public void setInsurancePeopleService(IInsurancePeopleService insurancePeopleService) {
		this.insurancePeopleService = insurancePeopleService;
	}

	private IInsuranceInsurancePeopleService insuranceInsurancePeopleService;
    
    public IInsuranceInsurancePeopleService getInsuranceInsurancePeopleService() {
		return insuranceInsurancePeopleService;
	}
    @Resource
	public void setInsuranceInsurancePeopleService(IInsuranceInsurancePeopleService insuranceInsurancePeopleService) {
		this.insuranceInsurancePeopleService = insuranceInsurancePeopleService;
	}

	private IInsuranceService insuranceService;
    public IInsuranceService getInsuranceService() {
        return insuranceService;
    }
    @Resource
    public void setInsuranceService(IInsuranceService insuranceService) {
        this.insuranceService = insuranceService;
    }

    @Resource
    private ICustomerService customerService;
    public ICustomerService getCustomerService() {
		return customerService;
	}
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	private IBrokerageRecordService brokerageRecordService;
	public IBrokerageRecordService getBrokerageRecordService() {
		return brokerageRecordService;
	}
	@Resource
	public void setBrokerageRecordService(IBrokerageRecordService brokerageRecordService) {
		this.brokerageRecordService = brokerageRecordService;
	}
	
	private ICarBrokerageRecordService carBrokerageRecordService;
	public ICarBrokerageRecordService getCarBrokerageRecordService() {
		return carBrokerageRecordService;
	}
	@Resource
	public void setCarBrokerageRecordService(ICarBrokerageRecordService carBrokerageRecordService) {
		this.carBrokerageRecordService = carBrokerageRecordService;
	}
	
	private IRoleEmployeeService roleEmployeeService;
	public IRoleEmployeeService getRoleEmployeeService() {
		return roleEmployeeService;
	}
	@Resource
	public void setRoleEmployeeService(IRoleEmployeeService roleEmployeeService) {
		this.roleEmployeeService = roleEmployeeService;
	}
	
	private ICooperationTeamService cooperationTeamService;
	public ICooperationTeamService getCooperationTeamService() {
		return cooperationTeamService;
	}
	@Resource
	public void setCooperationTeamService(ICooperationTeamService cooperationTeamService) {
		this.cooperationTeamService = cooperationTeamService;
	}
	
	private IShareBrokerageService shareBrokerageService;
	public IShareBrokerageService getShareBrokerageService() {
		return shareBrokerageService;
	}
	@Resource
	public void setShareBrokerageService(IShareBrokerageService shareBrokerageService) {
		this.shareBrokerageService = shareBrokerageService;
	}
	
	private ICarShareBrokerageService carShareBrokerageService;
	public ICarShareBrokerageService getCarShareBrokerageService() {
		return carShareBrokerageService;
	}
	@Resource
	public void setCarShareBrokerageService(ICarShareBrokerageService carShareBrokerageService) {
		this.carShareBrokerageService = carShareBrokerageService;
	}

	private final String indexViewName="index";
    private final String outputViewName="output";
    private final String detailedViewName="insuranceDetailed";
    private final String saveViewName="save";
    private final String deleteViewName = "delete";
    private final String queryInsurancePeopleIdViewName="queryInsurancePeopleId";
    private final String ceshiViewName = "ceshi";
    private final String insuranceViewName = "insurance";
    private final String allCustViewName = "allCust";
    private final String proportionViewName = "proportion";
    private final String shelfViewName = "shelf";
    private final String undercarriageViewName = "undercarriage";
    private final String insuranceMoneyViewName = "insuranceMoney";
    
    
    @RequestMapping(value = ceshiViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String ceshi(Model model,PagerModel pagerModel,InsuranceSearch search,boolean ajaxPost){
    	
        return view(ceshiViewName);
    }
    
    //传过来总比例 求出一级分享奖和推广奖比例
    @ResponseBody
    @RequestMapping(value = proportionViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String proportion(Model model,String total,boolean ajaxPost){
    	double tax =ExpressionUtil.stringToDouble(awardSettingService.queryModelByHC("tax",InsuranceType.NotCar).getExpression(), 0.00);
        double totalProportion=new BigDecimal(String.valueOf(total)).setScale(3, BigDecimal.ROUND_DOWN).doubleValue();
    	double proportion=tax*totalProportion;
    	double first =ExpressionUtil.stringToDouble(awardSettingService.queryModelByHC("firstShare",InsuranceType.NotCar).getExpression(), proportion);
    	double promote=ExpressionUtil.stringToDouble(awardSettingService.queryModelByHC("promote",InsuranceType.NotCar).getExpression(), proportion);
    	Insurance insurance=new Insurance();
    	insurance.setShareProportionOne(first);
    	insurance.setSpreadProportion(promote);
    	
    	return JsonUtils.toJson(insurance);
    }

	@RequestMapping(value = insuranceMoneyViewName, method = { RequestMethod.GET,RequestMethod.POST })
    @ResponseBody
    public String insuranceMoney(boolean ajaxPost,String state){
		HashMap<String,String> mp = new HashMap<String, String>();
		CustomerSearch customerSearch = new CustomerSearch();
		
		String loginId = getLoginModel().getLoginId();
	    String roleId = roleEmployeeService.queryRoleIdsByEmployeeId(loginId).get(0);
	    
	    //判断身份
	    if(LoginRole.HighMaker.equals(roleId)){
	    	customerSearch.setId(loginId);
	    	if("notcar".equals(state)){
				mp=shareBrokerageService.queryShareBrokerageForMoney(customerSearch);
			}else if("car".equals(state)){
				mp=carShareBrokerageService.queryCarShareBrokerageForMoney(customerSearch);
			}
	    }else {
	    	if(LoginRole.CityMaker.equals(roleId)){
	    		customerSearch.setCityId(cooperationTeamService.queryModel(loginId).getCityId());
	    	}
	    	
	    	if("notcar".equals(state)){
				mp=brokerageRecordService.queryBrokerageRecordForMoney(customerSearch);
			}else if("car".equals(state)){
				mp=carBrokerageRecordService.queryCarBrokerageRecordForMoney(customerSearch);
			}
	    }
	    
	    
    		
    	return JsonUtils.toJson(mp);
    }
	
	@RequestMapping(value = insuranceViewName, method = { RequestMethod.GET,RequestMethod.POST })
    @ResponseBody
    public String insurance(boolean ajaxPost,String state){
		HashMap<String,String> mp = new HashMap<String, String>();
		CustomerSearch customerSearch = new CustomerSearch();
		
		String loginId = getLoginModel().getLoginId();
	    String roleId = roleEmployeeService.queryRoleIdsByEmployeeId(loginId).get(0);
	    //判断身份
	   if(LoginRole.HighMaker.equals(roleId)){
	    	customerSearch.setId(loginId);
	    	if("notcar".equals(state)){
				mp=shareBrokerageService.queryShareBrokerageForStatistic(customerSearch);
			}else if("car".equals(state)){
				mp=carShareBrokerageService.queryCarShareBrokerageForStatistic(customerSearch);
			}
	    }else{
	    	if(LoginRole.CityMaker.equals(roleId)){
	    		customerSearch.setCityId(cooperationTeamService.queryModel(loginId).getCityId());
	    	}
	    	
	    	if("notcar".equals(state)){
				mp=brokerageRecordService.queryBrokerageRecordForStatistic(customerSearch);
			}else if("car".equals(state)){
				mp=carBrokerageRecordService.queryCarBrokerageRecordForStatistic(customerSearch);
			}
	    }
	    
    		
    	return JsonUtils.toJson(mp);
    }
    
    @RequestMapping(value = allCustViewName, method = { RequestMethod.GET,RequestMethod.POST })
    @ResponseBody
    public String allCust(boolean ajaxPost,String state){
    	    String loginId = getLoginModel().getLoginId();
    	    String roleId = roleEmployeeService.queryRoleIdsByEmployeeId(loginId).get(0);
    		
    	    CustomerSearch search = new CustomerSearch();
    	    //判断身份
    	    if(LoginRole.CityMaker.equals(roleId)){
    	    	search.setCityId(cooperationTeamService.queryModel(loginId).getCityId());
    	    }else if(LoginRole.HighMaker.equals(roleId)){
    	    	search.setRefereeId(loginId);
    	    }
    		
    		HashMap<String,String> map=customerService.queryAllCustCount(state,search);
            return JsonUtils.toJson(map);	
    }
    
    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,PagerModel pagerModel,InsuranceSearch search,boolean ajaxPost){

        pagerModel.setTotalAmount(insuranceService.queryInsuranceCount(search));
        List<Insurance> insurances= insuranceService.queryInsuranceList(search,pagerModel);
        System.out.println("=================search"+search);
        model.addAttribute(ManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("insurances", insurances);
        model.addAttribute("insuranceSearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(indexViewName);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String insuranceDetailed(Model model,String key){
        
    	Insurance insurance=new Insurance();
        if(!StringUtils.isEmpty(key)){
            insurance=insuranceService.queryModel(key);
            List<String> insurancePeopleIds = insuranceInsurancePeopleService.queryInsurancePeopleId(key);
            model.addAttribute("insurancePeopleIds",insurancePeopleIds);
        }else if(StringUtils.isEmpty(key)){
            insurance.setStatus(InsuranceStatus.newInsurance);
            insurance.setState(InsuranceState.grounding);
           
            insurance.setServerProportion(ExpressionUtil.stringToDouble(awardSettingService.queryModelByHC("server",InsuranceType.NotCar).getExpression(), 0.00));
            insurance.setHatchProportion(ExpressionUtil.stringToDouble(awardSettingService.queryModelByHC("hatch",InsuranceType.NotCar).getExpression(), 0.00));
            insurance.setShareProportionTwo(ExpressionUtil.stringToDouble(awardSettingService.queryModelByHC("secondShare",InsuranceType.NotCar).getExpression(), 0.00));
            insurance.setCityProportion(0.015);
           /* insurance.setCompanyProportion(0.02);*/
        }
        
        model.addAttribute("insurance", insurance);
        return view(detailedViewName);
    }

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,Insurance insurance){
    	
        if(StringUtils.isEmpty(insurance.getId())){
            insurance.setId(CommonUtils.getKeyId());
            insurance.setCreateDate(DateUtils.getCurrent());
            insurance.setDeleteMark(YesOrNo.no);
            insurance.setCreateName(getLoginModel().getLoginName());
            insurance.setModelStatus(ModelStatus.add);
        }else{
            insurance.setModifyDate(DateUtils.getCurrent());
            insurance.setModifyName(getLoginModel().getLoginName());
            insurance.setModelStatus(ModelStatus.update);
        }

        insurance.setCode(ChineseUtils.getPingYin(insurance.getInsuranceName()));
        insurance.setMarkCode(ChineseUtils.getPinYinHeadChar(insurance.getInsuranceName()));

        
        ActionResult actionResult;
        if(insuranceService.applyChange(insurance)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("insurance", insurance);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(detailedViewName);
    }

    @RequestMapping(value = queryInsurancePeopleIdViewName, method = { RequestMethod.GET,RequestMethod.POST},produces="text/plain;charset=utf-8")
   	@ResponseBody
   	public String queryInsurancePeopleId(String insuranceId){

    	List<InsurancePeople> insurancePeoples=insurancePeopleService.queryList();
    	return JsonUtils.toJson(insurancePeoples);
    }
    
    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(insuranceService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    //上架最近一次修改的产品
    @RequestMapping(value =shelfViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String shelf(InsuranceSearch insuranceSearch){
       String result=null;
       if(!StringUtils.isEmpty(insuranceSearch)){
    	int a=insuranceService.updateShelf(insuranceSearch);
    	if(a>=1){
    		result="success";
    	}else{
    		result="error";
    	}
       }else if(StringUtils.isEmpty(insuranceSearch)){
    	   result="error";
       }
      
        return JsonUtils.toJson(result);
    }
    
  //下架所有选择的产品
    @RequestMapping(value =undercarriageViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String undercarriage(InsuranceSearch insuranceSearch){
    	String result=null;
    	String channelName=insuranceSearch.getChannelName();
    	String insuranceName=insuranceSearch.getInsuranceName();
    	String insuranceOne=insuranceSearch.getInsuranceOne();
    	String insuranceTwo=insuranceSearch.getInsuranceTwo();
    	String status=insuranceSearch.getStatus();
    	
        if((!StringUtils.isEmpty(channelName)) || (!StringUtils.isEmpty(insuranceName))
        	|| (!StringUtils.isEmpty(insuranceOne)) || (!StringUtils.isEmpty(insuranceTwo))
        	|| (!StringUtils.isEmpty(status))){ 
     	int a=insuranceService.updateUndercarriage(insuranceSearch);
     	System.err.println("一共下架了"+a+"款产品");
     	if(a>=1){
     		result="success";
     	}else{
     		result="error";
     	}
        }else {
     	   result="error";
        }
        return JsonUtils.toJson(result);
    }
}
